<template>
  <view>
    <view class="navbar">
      <uni-nav-bar @clickLeft="goback" leftIcon="left" fixed="true" border="false" color="#FFF" statusBar="true"
        backgroundColor="#22b9a3" title="高考听力真题" />
    </view>
    <view class="container">
      <!-- 左侧分类 -->
      <view class="categories">
        <view :class="[selectedYear==year ? 'category-item-active' : '', 'category-item']"
          v-for="(year, index) in years" :key="year" @click="selectYear(year)">
          <view class="name">
            {{ year }}年真题
          </view>
        </view>
      </view>
      <!-- 右侧资源列表 -->
      <scroll-view class="products" scroll-y="true">
        <view class="product-item" 
          v-for="(resource, index) in resourcesList" :key="resource.id">
          <uni-section :title="resource.resourceName" type="circle" >
            <uni-card title="试卷" :isFull="true" thumbnail="/static/images/file/doc.png" extra="查看" @click="downloadAndOpen(resource.fileUrlOne)">        
            </uni-card>
            <uni-card title="音频" :isFull="true" thumbnail="/static/images/file/mp3.png" extra="查看" @click="downloadAndOpen(resource.fileUrlTwo)">
            </uni-card>
          </uni-section>
        </view>
      </scroll-view>
    </view>
  </view>

</template>

<script setup>
  import * as http from '@/utils/http'
  import {
    ref
  } from 'vue';
  import {
    onLoad
  } from '@dcloudio/uni-app'
  //获取书籍
  const years = ref([])
  //加载页面
  onLoad(async (option) => {
    //获取听力资源
    const result = await http.getRequest("/xhyy/beikao/getYear", {
      type: 1
    })
    if (result.code == 0) {
      years.value = result.data
    } else {
      uni.showToast({
        title: '获取资源失败',
        icon: 'error',
        duration: 1000
      })
    }
    //设置最早的年份为第一年
    selectYear(years.value[0])
  })
  // 默认选
  const selectedyear = ref(0);

  function selectYear(id) {
    selectedyear.value = id;
    //根据年份去获取对应的资源
    fetchResourceByyear()
  }
  //获得资源
  const resourcesList = ref([]);

  async function fetchResourceByyear() {
    resourcesList.value = []
    const API = '/xhyy/beikao/page'
    const result = await http.getRequest(API, {
      year: selectedyear.value,
      type: 1,
      pageNo: 1,
      pageSize: 20
    })
    if (result.code == 0) {
      resourcesList.value = result.data.list
    } else {
      uni.showToast({
        title: '资源失败',
        icon: 'error',
        duration: 1000
      })
    }
  }

  function goback() {
    uni.navigateBack()
  }
  
const loading = ref(false)

// 下载并打开文件
const downloadAndOpen = async (fileUrl) => {
  if (loading.value) return
  loading.value = true
  try {
    uni.showLoading({
      title: '准备文件中...',
      mask: true
    })

    // 下载文件
    const { tempFilePath } = await new Promise((resolve, reject) => {
      wx.downloadFile({
        url: fileUrl,
        success: resolve,
        fail: reject
      })
    })
  // 方法2: 从原始URL判断
  const urlFileName = fileUrl.split('/').pop() || ''
  const urlExtension = urlFileName.toLowerCase().split('.').pop()
  // 音频文件类型
    const audioExtensions = ['mp3', 'wav', 'aac', 'm4a', 'ogg', 'flac']
    // 文档文件类型
    const documentExtensions = ['docx', 'doc', 'pdf', 'txt', 'ppt', 'pptx', 'xls', 'xlsx']
  if(documentExtensions.includes(urlExtension)){
    // 使用微信开放能力打开文档
    wx.openDocument({
      filePath: tempFilePath,
      fileType: 'docx',
      success: () => {
        console.log('打开文档成功')
      },
      fail: (err) => {
        console.error('打开失败:', err)
        uni.showToast({
          title: '打开失败',
          icon: 'none'
        })
      }
    })
  }else if(audioExtensions.includes(urlExtension)){
    wx.openDocument({
          filePath: tempFilePath,
          fileType: 'audio', // 指定为音频类型
          success: () => {
            console.log('已调用系统播放器')
            uni.showToast({
              title: '正在播放',
              icon: 'success'
            })
          },
          fail: (err) => {
            console.error('打开失败:', err)
            uni.showToast({
              title: '打开失败',
              icon: 'none',
              duration: 3000
            })
          }
        })
  }
  } catch (error) {
    console.error('操作失败:', error)
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
    uni.hideLoading()
  }
}
//跳转到详情页
  function gotoSeeFile(resourceId){
    uni.navigateTo({
      url:`/pages/detail/hearingDetail/hearingDetail?resourceId=${resourceId}`
    })
  }
</script>

<style lang="scss" scoped>
  .navbar ::v-deep .uni-nav-bar-text {
    font-size: $uni-font-size-title !important;
    font-family: "siyuan";
  }

  .type {
    background-color: $uni-bg-color-grey;
  }

  .container {
    display: flex;
    padding: 22rpx;
    border-radius: 10rpx;
    height: 100vh;
  }

  .categories {
    width: 173rpx;
    background-color: #fff;
    height: 100vh;
  }

  .category-item {
    cursor: pointer;

    .name {
      height: 87rpx;
      line-height: 87rpx;
      width: 200rpx;
      font-family: SourceHanSansSC-Regular;
      font-size: 28rpx;
      text-align: left;
      padding-left: 8rpx;
      color: #858685;

    }
  }

  .category-item-active {
    border-left: 7rpx solid #22b9a3;

    .name {
      color: #22b9a3;
    }
  }

  .product-item {
    position: relative;
    display: flex;
    align-items: center;
    margin-bottom: 25.5rpx;
    padding: 17rpx;
    border: 1px solid #eee;
    border-radius: 9rpx;
    background-color: #fff;
  }

  .product-image {
    width: 150rpx;
    height: 180rpx;
    margin-right: 25.5rpx;
  }

  .product-image image {
    width: 150rpx;
    height: 180rpx;
  }


  .product-name {
    text-align: center;
    font-size: 27.2rpx;
    font-weight: bold;
    margin-bottom: 9px;
  }

  .buy-button {
    position: absolute;
    right: 140rpx;
    bottom: 15rpx;
    display: inline-block;
    width: 150rpx;
    height: 50rpx;
    line-height: 50rpx;
    background-color: #24c373;
    border-radius: 30rpx;
    font-size: 25rpx;
    color: #fff;
    letter-spacing: 3.5rpx;
    text-align: center;

  }
</style>